package com.zqwm.fly.service;

import java.io.BufferedReader;
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.UnsupportedEncodingException;  
import java.net.MalformedURLException;  
import java.net.URL;  
import java.net.URLConnection;  
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
   
public class WeatherInfo
{
    private Integer error;
    private String status;
    private String date;
    private String PM25;
    private String currentCity;
    private List<Index> indexs;//指数
    private List<WeatherData> weather_data;
    private String baiduUrl;

    public WeatherInfo(String cityName)
    {
        //百度天气API
        StringBuffer strBuf;
        try{
            baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=3ade97d039bfed0954d46242ed319c67";
            strBuf = new StringBuffer();

            URL url = new URL(baiduUrl);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                strBuf.append(line.trim());
                JSONObject dataJson = new JSONObject(strBuf.toString());// 创建一个包含原始json串的json对象
                System.out.println(dataJson.toString());
                this.status=(String) dataJson.get("status");
                if("success".equals(this.status))//如果状态正常
                {
                    this.date =(String) dataJson.get("date");
                    JSONArray results=dataJson.getJSONArray("results");
                    JSONObject resultObj=results.getJSONObject(0);
                    this.currentCity = resultObj.getString("currentCity");
                    this.PM25 = resultObj.getString("pm25");

                    JSONArray weather_data = resultObj.getJSONArray("weather_data");
                    JSONArray index = resultObj.getJSONArray("index");

                    for(int j=0;j<index.length();j++)
                    {
                        this.indexs = new ArrayList<Index>();
                        JSONObject indexObj = index.getJSONObject(j);
                        String des =(indexObj.has("des")==true)?indexObj.getString("des"):null;
                        Index index1 = new Index(indexObj.getString("title"),indexObj.getString("zs"), indexObj.getString("tipt"),des);
                        this.indexs.add(index1);
                    }

                    for(int i=0;i<weather_data.length();i++)
                    {
                        this.weather_data = new ArrayList<WeatherData>();
                        JSONObject weathers = weather_data.getJSONObject(i);
                        WeatherData weatherData =new WeatherData(weathers.getString("date"),weathers.getString("dayPictureUrl"),weathers.getString("nightPictureUrl"),weathers.getString("weather"),weathers.getString("wind"),weathers.getString("temperature"));
                        this.weather_data.add(weatherData);
                    }
                }
            }
            reader.close();
        }catch(MalformedURLException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 穿衣指标类
     */
    class Index
    {
        private String title;
        private String zs;
        private String tipt;
        private String des;

        public Index(String title, String zs, String tipt, String des)
        {
            this.title = title;
            this.zs = zs;
            this.tipt = tipt;
            this.des = des;
        }

        public String getTitle(){return title;}
        public void setTitle(String title) {this.title = title;}
        public String getZs() {return zs;}
        public void setZs(String zs) {this.zs = zs;}
        public String getTipt(){return tipt;}
        public void setTipt(String tipt) {this.tipt = tipt;}
        public String getDes() {return des;}
        public void setDes(String des) {this.des = des;}
    }

    /**
     * 近几天的天气情况
     */
    class WeatherData
    {
        private String date;
        private String dayPictureUrl;
        private String nightPictureUrl;
        private String weather;
        private String wind;
        private String temperature;

        public WeatherData(String date, String dayPictureUrl, String nightPictureUrl, String weather, String wind, String temperature)
        {
            this.date = date;
            this.dayPictureUrl = dayPictureUrl;
            this.nightPictureUrl = nightPictureUrl;
            this.weather = weather;
            this.wind = wind;
            this.temperature = temperature;
        }

        public String getDate() {return date;}
        public void setDate(String date) {this.date = date;}
        public String getDayPictureUrl() {return dayPictureUrl;}
        public void setDayPictureUrl(String dayPictureUrl) {this.dayPictureUrl = dayPictureUrl;}
        public String getNightPictureUrl() {return nightPictureUrl;}
        public void setNightPictureUrl(String nightPictureUrl) {this.nightPictureUrl = nightPictureUrl;}
        public String getWeather() {return weather;}
        public void setWeather(String weather) {this.weather = weather;}
        public String getWind() {return wind;}
        public void setWind(String wind) {this.wind = wind;}
        public String getTemperature() {return temperature;}
        public void setTemperature(String temperature) {this.temperature = temperature;}
    }

	  //根据城市获取天气信息的java代码  
      //cityName 是你要取得天气信息的城市的中文名字，如“北京”，“深圳”  
public static String  getWeatherInform(String cityName){  

  //百度天气API  
  String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";  
  StringBuffer strBuf;
  String tqyb = "";

  try {                              
                      //通过浏览器直接访问http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ  
                      //5slgyqGDENN7Sy7pw29IUvrZ 是我自己申请的一个AK(许可码)，如果访问不了，可以自己去申请一个新的ak  
                      //百度ak申请地址：http://lbsyun.baidu.com/apiconsole/key  
                      //要访问的地址URL，通过URLEncoder.encode()函数对于中文进行转码                              
      baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=3ade97d039bfed0954d46242ed319c67";
      System.out.println(baiduUrl);
  } catch (UnsupportedEncodingException e1) {               
      e1.printStackTrace();                     
  }  

  strBuf = new StringBuffer();  
        
  try{  
      URL url = new URL(baiduUrl);  
      URLConnection conn = url.openConnection();  
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。  
      String line = null;  
      while ((line = reader.readLine()) != null)
      {
    	  strBuf.append(line.trim());
    	  JSONObject dataJson = new JSONObject(strBuf.toString());// 创建一个包含原始json串的json对象 
    	  String newdate=(String) dataJson.get("date");
    	  String status=(String) dataJson.get("status");
          JSONArray results=dataJson.getJSONArray("results");
          JSONObject resultObj=results.getJSONObject(0);
          String currentCity = resultObj.getString("currentCity");
          String pm25 = resultObj.getString("pm25");
          StringBuffer indexBuf = new StringBuffer();  
          StringBuffer weatherBuf = new StringBuffer();
          
          JSONArray weather_data = resultObj.getJSONArray("weather_data");
          JSONArray index = resultObj.getJSONArray("index");
          
          for(int j=0;j<index.length();j++)
          {
        	  JSONObject indexObj = index.getJSONObject(j);
        	  String title = indexObj.getString("title");
        	  String zs = indexObj.getString("zs");
        	  String tipt = indexObj.getString("tipt");
        	  String des = indexObj.getString("des");
        	  if(!"紫外线强度".equals(title)&&!"洗车".equals(title)){indexBuf.append(des);}
        	  
        	  
          }
          
          for(int i=0;i<weather_data.length();i++)
          {
	          JSONObject weathers = weather_data.getJSONObject(i);
	          String wind = weathers.getString("wind");
	          String dayPictureUrl = weathers.getString("dayPictureUrl");
	          String weather =weathers.getString("weather");
	          String nightPictureUrl = weathers.getString("nightPictureUrl");
	          String date = weathers.getString("date");
	          String temperature = weathers.getString("temperature");
	          weatherBuf.append(date+weather+wind+" 温差 "+temperature);
          }
          
           tqyb = "今天是"+newdate+"，你所在的"+currentCity+"城市当前pm2.5为"+pm25+","+weatherBuf.toString()+indexBuf.toString()+"-----最求完美";
          System.out.println(tqyb);
          System.out.println(strBuf.toString());
          
          
      }
      reader.close();
  }catch(MalformedURLException e) {  
      e.printStackTrace();   
  }catch(IOException e){  
      e.printStackTrace();   
  }     

  return tqyb;  
}
    public Integer getError() {return error;}
    public void setError(Integer error) {this.error = error;}
    public String getStatus() {return status;}
    public void setStatus(String status) {this.status = status;}
    public String getDate() {return date;}
    public void setDate(String date) {this.date = date;}
    public String getPM25() {return PM25;}
    public void setPM25(String PM25) {this.PM25 = PM25;}
    public String getCurrentCity() {return currentCity;}
    public void setCurrentCity(String currentCity) {this.currentCity = currentCity;}
    public List<Index> getIndexs() {return indexs;}
    public void setIndexs(List<Index> indexs) {this.indexs = indexs;}
    public List<WeatherData> getWeather_data() {return weather_data;}
    public void setWeather_data(List<WeatherData> weather_data) {this.weather_data = weather_data;}

    public static void main(String[] args) throws IOException {
        	getWeatherInform("长安镇");
		}
  }
